﻿using AspNetTraining.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AspNetTraining
{
    public partial class UserAccountDetail : System.Web.UI.Page
    {
        UserAccountManager useracc = new UserAccountManager();
        UserAccount thisUserAccount = new UserAccount();
        int[] thang = new int[] { 
        31,28,31,30,31,30,31,31,30,31,30,31
        };
        public UserAccount SessionLogin
        {
            get
            {
                return (UserAccount)Session["LoggedUser"];
            }
            set
            {
                Session["LoggedUser"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // load giu lieu len combobox
            if (!IsPostBack)
            {
                GroupUserManager groupuser = new GroupUserManager();
                List<GroupUser> Lgroupuser = groupuser.GetGroupUser();
                foreach (GroupUser g in Lgroupuser)
                {
                    ddlGroupUser.Items.Add(new ListItem(g.GroupName, g.GroupUserID.ToString()));
                }
            }
            if (Request["id"] != null)
            {
                //luu lai user cu.
                thisUserAccount = useracc.GetAccountByID(new Guid(Request["id"]));
                if (!IsPostBack)
                {
                    // set gia tri len form 
                    SetValue(thisUserAccount); 
                }
            }
            else
            {
                btnUpdate.Text = "Create";
                txtUserName.Enabled = true;
            }           
        }
        public void SetValue(UserAccount account)
        {
            txtUserName.Text = account.UserName;
            txtFirstName.Text = account.FirstName;
            txtLastName.Text = account.LastName;
            ddlGroupUser.SelectedValue = account.GroupUserID.ToString();
            txtEmail.Text = account.Email;
            DdlMonths.Text = account.Birthday.Value.Month.ToString();
            txtDay.Text = account.Birthday.Value.Day.ToString();
            txtYear.Text = account.Birthday.Value.Year.ToString();
            txtCreatedOn.Text = account.CreatedOn.ToString();
            txtConfirmPassword.Attributes["value"] =  account.Password;
            txtPassword.Attributes["value"] = account.Password;
            
            //if (account.CreatedBy!=null)
            //    txtCreatedBy.Text = useracc.GetUserNameByUserID(new Guid(account.CreatedBy));
           
            txtModifiedOn.Text = account.ModifiedOn.ToString();
            //if (account.ModifiedBy!=null)
            //    txtModifiedBy.Text = useracc.GetUserNameByUserID((Guid)(account.ModifiedBy));
            txtDescription.Text = account.Description;
            chkActive.Checked = (bool)account.Active;
            string s = txtDay.Text + "/" + DdlMonths.SelectedValue + "/" + txtYear.Text;
        }

        protected String GetGroupUserByID(object ID)
        {
            GroupUserManager groupuser = new GroupUserManager();
            return groupuser.GetGroupUserNameByID(new Guid(ID.ToString()));
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            #region Check ngay thang nam sinh
            try {
                int nam = int.Parse(txtYear.Text);
                if ((nam % 4 == 0 && nam % 100 != 0) || nam % 400 == 0)
                    thang[1] = 29;
            }
            catch { }
           
                int i = int.Parse(DdlMonths.SelectedValue);
                if (i > 0)
                {
                    try
                    {
                        if (int.Parse(txtDay.Text) > thang[i - 1])
                        {
                            lblError.Text = "Ngày sinh không hợp lệ.";
                            lblError.ForeColor = System.Drawing.Color.Red;
                            return;
                        }
                    }
                    catch
                    {
                        lblError.Text = "Ngày sinh không hợp lệ.";
                        lblError.ForeColor = System.Drawing.Color.Red;
                        return;
                    }

                }
                else
                {
                    lblError.Text = "Chọn tháng sinh.";
                    lblError.ForeColor = System.Drawing.Color.Red;
                    return;
                }
            #endregion
            if (txtPassword.Text == txtConfirmPassword.Text)
            {
                UserAccount user = new UserAccount();
                user.UserAccountID = thisUserAccount.UserAccountID;
                user.UserName = txtUserName.Text;
                user.FirstName = txtFirstName.Text;
                user.LastName = txtLastName.Text;
                user.FullName = user.FirstName + user.LastName;
                user.GroupUserID = ddlGroupUser.SelectedValue;
                user.Email = txtEmail.Text;
                user.Birthday = DateTime.Parse(DdlMonths.SelectedValue + "/" + txtDay.Text + "/" + txtYear.Text);
                user.Description = txtDescription.Text;
                user.Active = chkActive.Checked;
                user.Password = txtPassword.Text;

                txtDay.Text = user.Birthday.Value.Month.ToString();
                DdlMonths.Text = user.Birthday.Value.Day.ToString();
                txtYear.Text = user.Birthday.Value.Year.ToString();

                user.Builtin = thisUserAccount.Builtin;
                try
                {
                    // kiem tra id neu id not null thi dang la sua mot user va nguoc lai
                    if (Request["id"] != null)
                    {
                        user.CreatedBy = thisUserAccount.CreatedBy;
                        user.CreatedOn = DateTime.Parse(txtCreatedOn.Text);
                        user.ModifiedBy = SessionLogin.UserAccountID;
                        user.ModifiedOn = DateTime.Now;
                        useracc.UpDateUserAccount(user);
                        Response.Redirect("~/UserAccounts.aspx");
                    }
                    else
                    {
                        // check user name xem ton tai hay chua
                        if (useracc.CheckUserAccount(user.UserName))
                        {
                            user.CreatedBy = SessionLogin.UserAccountID.ToString();
                            user.CreatedOn = DateTime.Now;
                            user.UserAccountID = Guid.NewGuid();
                            useracc.InsertUserAccount(user);
                            Response.Redirect("~/UserAccounts.aspx");
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "alert(\"Account already exists. Selected a different account.\")", true);
                        }
                    }
                }
                catch { }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "alert(\"Passwords don't match.\")", true);
                return;    
            }
                    
        }
        protected void btnExit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UserAccounts.aspx");
        }
    }
}